/*    file: CRtpSink.h
 *    desc:
 *   
 * created: 2013-09-02 10:11:34
 *  author: zhengchuanjiang
 * company: 
 */ 


#if !defined CRTPSINK_ZHENGCHUANJIANG_
#define CRTPSINK_ZHENGCHUANJIANG_

#include "JRTPSession.h"

#include <TThread.h>
#include <TCriticalSection.h>
#include <TEvent.h>

#include "JRTPSession.h"
#include "RtpSink.h"
#include "RtpRecvState.h"

#include "OrderCache.h"
#include "RtpFileWriter.h"
#include "SharedPtr.h"

////////////////////////////////////////////////////////////////////////////
class CRtpSink : public comn::Thread
{
public:
    CRtpSink();
    virtual ~CRtpSink();

    void setProc(RtpSinkProc proc, void* pContext);

    bool open(uint16_t port, const char* svrIP, uint16_t svrPort);

    void close();

    void pause(bool toPause);

    void setCacheSize(size_t length);

    bool startRecord(const char* filename);

    void stopRecord();

	//void setDefaultTimestampIncrement(uint32_t )
	void setPayload(uint8_t payload);

	int sendPacket(const void *data, size_t len);

	int sendPacket(const void *data, size_t len,
		uint8_t pt, bool mark, uint32_t timestampinc);

protected:
    virtual void onRtpPacket(jrtplib::RTPPacket* pPacket);
    virtual void dealRtpPacket(jrtplib::RTPPacket* pPacket);

    virtual void dealRtpTimeout();

    virtual void onStreamPacket(int type, unsigned char* buffer, int length, uint32_t timestamp, bool marker);
    virtual void onEndOfStream();

	jrtplib::RTPPacket* pretranslatePacket(jrtplib::RTPPacket* pPacket);

protected:
    virtual int run();
    virtual void doStop();
    virtual bool startup();

    bool openRtpSession(uint16_t port);
    void closeRtpSession();

    void clearCache();

	void tracePacket(jrtplib::RTPPacket* pPacket);

    void prepareNAT();

protected:
	JRTPSession* m_pRtpSession;

    RtpSinkProc m_sinkProc;
    void*   m_pContext;

    uint16_t    m_port;

    bool m_paused;

    RtpRecvState   m_recvState;

    OrderCache      m_orderCache;
    comn::CriticalSection   m_cs;    

	uint16_t	m_lastSeq;

    std::string m_svrIP;
    uint16_t    m_svrPort;

    comn::CriticalSection m_csSink;
	
	std::shared_ptr<RtpFileWriter>	m_fileWriter;

	uint8_t	m_payload;

};
////////////////////////////////////////////////////////////////////////////
#endif //CRTPSINK_ZHENGCHUANJIANG_

